package com.kehongborui.reflecttion;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 通过反射获取的构造方法创建对象
 */
public class RefConstructorToInstanceTest {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class clazz = Class.forName("com.kehongborui.reflecttion.Student");  //
        Constructor constructor = clazz.getConstructor(null); // 获取学生类的构造方法
        Student student = (Student) constructor.newInstance(); // 通过构造方法创建对象
        student.setName("jack");
        System.out.println(student.getName());

        Constructor privateConstructor = clazz.getDeclaredConstructor(String.class); // 获取学生类的构造方法
        privateConstructor.setAccessible(true);
        student = (Student) privateConstructor.newInstance("rose"); // 通过私有的构造方法创建对象
        System.out.println(student.getName());
    }
}
